# -*- coding: utf-8 -*-
"""
分页工具
@api-version: 1.0.0
"""

from flask import request
from math import ceil

def paginate_query(query, page=None, per_page=None, max_per_page=100):
    """分页查询工具"""
    if page is None:
        page = request.args.get('page', 1, type=int)
    if per_page is None:
        per_page = request.args.get('pageSize', 20, type=int)
    
    # 限制每页最大数量
    if per_page > max_per_page:
        per_page = max_per_page
    
    # 确保页码和每页数量为正数
    page = max(1, page)
    per_page = max(1, per_page)
    
    # 执行分页查询
    total = query.count()
    items = query.offset((page - 1) * per_page).limit(per_page).all()
    
    # 计算总页数
    total_pages = ceil(total / per_page) if total > 0 else 1
    
    return {
        'items': items,
        'total': total,
        'page': page,
        'pageSize': per_page,
        'totalPages': total_pages
    }

def get_pagination_params():
    """获取分页参数"""
    page = request.args.get('page', 1, type=int)
    page_size = request.args.get('pageSize', 20, type=int)
    
    # 参数验证
    page = max(1, page)
    page_size = max(1, min(page_size, 100))  # 限制最大100条
    
    return page, page_size